#ifndef __HTTPD_SERVER__
#define __HTTPD_SERVER__

#include <pthread.h>
#include "ProtocolUtil.hpp"
#include "ThreadPool.hpp"

class HttpdServer{
private:
    int listen_sock;
    int port;

public:
    HttpdServer(int _port)
    :listen_sock(-1)
    ,port(_port)
    {}

    void InitServer()
    {
        listen_sock = socket(AF_INET, SOCK_STREAM, 0);
        std::cout << "listen_sock = "<<listen_sock<<std::endl;
        if(listen_sock < 0)
        {
            LOG(ERROR, "create sock failed!");
            exit(2);
        }

        int opt_ = 1;
        setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR, &opt_, sizeof(opt_));
        //reuse the ip when bind error

        struct sockaddr_in local_;
        local_.sin_family = AF_INET;
        local_.sin_port = htons(port);
        local_.sin_addr.s_addr = INADDR_ANY;//bind every enth in the Server; 
        //descrip part

        if(bind(listen_sock, (struct sockaddr*)&local_, sizeof(local_)) < 0)
        {
            LOG(ERROR, "bind socket failed!");
            exit(3);
        }
        //bind part

        if(listen(listen_sock, 5) < 0)
        {
            LOG(ERROR, "lsiten socket failed!");
            exit(4);
        }
        //listen part

        LOG(INFO, "initserver successful!");
    }

    void Start(ThreadPool*& tp_)
    {
        LOG(INFO, "Start Server Begin!");
        for(; ;){
            struct sockaddr_in client_;
            socklen_t len_ = sizeof(client_);
            int sock_ = accept(listen_sock, (struct sockaddr*)&client_, &len_);
            if(sock_ < 0)
            {
                LOG(WARNING, "accept filed!");
                continue;
            }         
            Task task;
            task.SetTask(sock_, Entry::HandlerProcess);
            tp_->PushTask(task);
        }
    }

    ~HttpdServer()
    {
        if(listen_sock != -1){
            close(listen_sock);
        }
        port = -1;
    }
};
#endif


